package com.hx.vending.util;

import com.hx.vending.bean.*;
import com.hx.vending.bean.config.Constants;
import com.hx.vending.dao.*;
import com.hx.vending.pay.WXPayUtil;
import com.hx.vending.service.IWXPayService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/1/3.
 * 支付超时
 */
public class payOverTime {

    private Logger logger = Logger.getLogger(payOverTime.class); // 获取logger实例

    @Autowired
    private OnlineOrderMapper onlineOrderMapper;

    @Autowired
    private UserWithdrawMapper userWithdrawMapper;

    @Autowired
    private IWXPayService iwxPayService;

    @Autowired
    private UserMapper userMapper;

    @Resource
    private MedicineMapper medicineMapper;

    @Resource
    private OrderBuyMapper orderBuyMapper;

    public void payOverTime(){

        //////////////////////////////////////订单超时///////////////////////////////////////////
        //查询所有未完成,并且超过两小时的订单
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //微信支付订单超时时间为两小时
        calendar.add(calendar.HOUR, -2);
        //System.out.println(sdf.format(calendar.getTime())+"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

        OnlineOrder onlineOrder = new OnlineOrder();
        onlineOrder.setOnlineOrderState(0);//未支付的
        onlineOrder.setOnlineOrderTime(sdf.format(calendar.getTime()));

        List<OnlineOrder> onlineOrderList = this.onlineOrderMapper.selectByPayOverTime(onlineOrder);

        if (ToolUtil.isNotEmpty(onlineOrderList) && onlineOrderList.size() > 0) {
            for (OnlineOrder order: onlineOrderList) {
                //直接删除不保留了
                this.medicineMapper.deleteByOrderId(order.getOnlineOrderId());

                this.onlineOrderMapper.deleteByPrivate(order.getOnlineOrderId());

                this.orderBuyMapper.deleteByParentId(order.getOnlineOrderId());
            }
        }


        //////////////////////////////////////提现失败///////////////////////////////////////////
        UserWithdraw userWithdraw = new UserWithdraw();
        userWithdraw.setUserWithdrawState(1);//处理中
        userWithdraw.setUserWithdrawType(0);//微信提现到零钱
        List<UserWithdraw> userWithdraws = this.userWithdrawMapper.selectByExample(userWithdraw);

        if (ToolUtil.isNotEmpty(userWithdraws)) {
            for (UserWithdraw forUserWithdraw: userWithdraws) {
                try {
                    //32位随机字符串
                    String TransferNonceStr = WXPayUtil.generateNonceStr(32);

                    SortedMap<String,String> transferData=new TreeMap<String,String>();

                    //随机字符串
                    transferData.put("nonce_str", TransferNonceStr);
                    //商户订单号要使用原商户订单号
                    transferData.put("partner_trade_no", forUserWithdraw.getUserWithdrawOutBizNo());
                    //商户号
                    transferData.put("mch_id", Constant.WX_MCH_ID);
                    //appid
                    transferData.put("appid", Constant.APPID);

                    //生成签名
                    String transferSign = WXPayUtil.generateSignature(transferData, Constant.KEY, Constants.SignType.MD5);
                    //发送给微信的xml
                    String transferOutputxml = WXPayUtil.mapToXml(transferData,transferSign);
                    //发送xml获取返回结果
                    String transferResource = this.getClass().getClassLoader().getResource("/").getPath();
                    String selectTransferInfo = WXPayUtil.requestOnce(Constant.GETTRANSFERINFO, TransferNonceStr, transferOutputxml, 6000, 8000, true, transferResource);
                    //将返回的xml转换为map
                    Map<String, String> transferResultMap = WXPayUtil.xmlToMap(selectTransferInfo);
                    if (ToolUtil.isNotEmpty(transferResultMap) && ToolUtil.isNotEmpty(transferResultMap.get("status"))) {
                        logger.error("检测提现"+transferResultMap.get("status"));
                        if (transferResultMap.get("status").equals("SUCECSS")) {//转账成功
                            forUserWithdraw.setUserWithdrawState(2);
                            forUserWithdraw.setUserWithdrawRemark("提现成功");
                        }else if (transferResultMap.get("status").equals("FAILED")) {//转账失败
                            forUserWithdraw.setUserWithdrawState(0);//失败
                            forUserWithdraw.setUserWithdrawRemark("提现失败");
                            //提现失败将提现的钱返还给用户
                            User user = new User();
                            user.setUserId(forUserWithdraw.getUserWithdrawUserid());
                            User selectUser = this.userMapper.selectByPrimaryKey(user);
                            if (ToolUtil.isNotEmpty(selectUser)) {
                                user.setUserMoney(BigDecimalUtils.add(user.getUserMoney(), forUserWithdraw.getUserWithdrawMoney()));
                                user.setUserWechatBalance(BigDecimalUtils.add(user.getUserWechatBalance(), forUserWithdraw.getUserWithdrawMoney()));
                                this.userMapper.updateByPrimaryKeySelective(user);
                            }
                        }else if (transferResultMap.get("status").equals("PROCESSING")) {//正在处理
                            forUserWithdraw.setUserWithdrawState(1);//处理中
                            forUserWithdraw.setUserWithdrawRemark("处理中");
                            //重新提现
                            this.iwxPayService.wxCashWithdrawal(forUserWithdraw.getUserWithdrawUserid(), forUserWithdraw.getUserWithdrawMoney(), forUserWithdraw.getUserWithdrawId());
                        }
                        userWithdrawMapper.updateByPrimaryKeySelective(forUserWithdraw);
                    }else {
                        forUserWithdraw.setUserWithdrawState(1);
                        forUserWithdraw.setUserWithdrawRemark("处理中");
                        userWithdrawMapper.updateByPrimaryKeySelective(forUserWithdraw);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

    }
}
